/**
 * 导入仓库 url方式
 * @param type 默认normal, retry：重新导入
 * @param projectInfo 默认为null，默认数据，在重新导入时用到
 * @param retryCallback 重新导入成功的回调
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Message, Tag, Balloon, Button } from '@teamix/ui';
import { navigateHref } from 'utils/router';
import SensitiveForm from './sensitive';
import DependencyForm from './dependency';
import PinpointForm from './pinpoint';
import { saveProjectServices, openPinpoint, postServiceLog } from 'api';
import GuaranteeModal from 'components/guaranteeModal';
import './index.scss';
import intl from '../../locale';

export default class ProejctSecuritySettingModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
    data: PropTypes.object,
  };

  static defaultProps = {
    trigger: null,
    closeModal: () => {},
    data: {},
  };

  constructor(props) {
    super(props);
    this.state = {
      submitting: false,
      isModalOpen: false,
      isServiceModalOpen: false,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  setSubmitting = (submitting) => {
    this.setState({
      submitting,
    });
  };

  handleOk = () => {
    const { data, modalPlugin } = this.props;
    const { submitting } = this.state;
    if (submitting) {
      return;
    }

    const { key, params } = this.form.getReqData();
    this.setSubmitting(true);

    let openSerivcePromise;
    if (key === 'pinpoint_detection') {
      openSerivcePromise = openPinpoint(params);
    } else {
      const isServiceOpen = data[key] && data[key].enabled;
      const switchPromise = isServiceOpen
        ? Promise.resolve()
        : postServiceLog({
            service: key,
            authorized: true,
          });

      openSerivcePromise = switchPromise.then(() => {
        return saveProjectServices({
          integration_service_setting: {
            ...data,
            [key]: params,
          },
        });
      });
    }

    openSerivcePromise
      .then(() => {
        this.setSubmitting(false);
        Message.success({
          title: intl.get({
            id: 'code-assets.components.projectSecuritySettingModal.SavedSuccessfully',
            defaultMessage: '保存成功',
          }),
        });

        const { pathResource } = window.FORCE;
        navigateHref(`/${pathResource.fullPath}/project_security/${
          modalPlugin._path
        }/master${modalPlugin.isCodeup ? '' : '?initial=true'}`);
      })
      .catch(() => {
        this.setSubmitting(false);
      });
  };

  render() {
    const { modalPlugin, data } = this.props;
    const { disabled, isServiceModalOpen, submitting } = this.state;
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={
              <div className="security-setting-modal-title">
                {modalPlugin.isCodeup ? (
                  <Tag className="security-setting-modal-title-left">
                    {intl.get({
                      id: 'code-assets.components.projectSecuritySettingModal.BuiltIn',
                      defaultMessage: '内置',
                    })}
                  </Tag>
                ) : (
                  <Balloon.Tooltip
                    align="t"
                    trigger={
                      <img
                        className="flow-img security-setting-modal-title-left"
                        src="https://tcs-devops.aliyun.com/thumbnail/111r5654e7a3c12aa319236976eb9530c2cf/w/88/h/88"
                      />
                    }
                  >
                    {intl.get({
                      id: 'code-assets.components.projectSecuritySettingModal.CloudEffectPipelineFlowSupport',
                      defaultMessage: '云效流水线 Flow 支持',
                    })}
                  </Balloon.Tooltip>
                )}
                {intl.get({
                  id: 'code-assets.components.projectSecuritySettingModal.SetDetectionParameters',
                  defaultMessage: '设置检测参数',
                })}
              </div>
            }
            shouldUpdatePosition
            visible
            style={{ width: '696px' }}
            onClose={this.onClose}
            footer={
              <div className="security-setting-modal-footer">
                <div>
                  {intl.get({
                    id: 'code-assets.components.projectSecuritySettingModal.AcceptUponDetection',
                    defaultMessage: '执行检测即同意',
                  })}

                  <a
                    className={'no-href-with-click'}
                    onClick={(e) => {
                      e.stopPropagation();
                      this.setState({
                        isServiceModalOpen: true,
                      });
                    }}
                  >
                    {intl.get({
                      id: 'code-assets.components.projectSecuritySettingModal.ServiceActivationAgreement',
                      defaultMessage: '服务开通协议',
                    })}
                  </a>
                </div>
                <div>
                  <Button
                    type="normal"
                    className="security-setting-modal-footer-cancel"
                    onClick={this.onClose}
                  >
                    {intl.get({
                      id: 'code-assets.components.projectSecuritySettingModal.Cancel',
                      defaultMessage: '取消',
                    })}
                  </Button>
                  <Button
                    type="primary"
                    onClick={this.handleOk}
                    loading={!!submitting}
                    disabled={disabled}
                  >
                    {intl.get({
                      id: 'code-assets.components.projectSecuritySettingModal.PerformDetection',
                      defaultMessage: '执行检测',
                    })}
                  </Button>
                </div>
              </div>
            }
            className="security-setting-modal"
            ref={(ref) => {
              this.dialog = ref;
            }}
          >
            {modalPlugin.key === 'sensitive_info_detection' && (
              <SensitiveForm
                ref={(ref) => {
                  this.form = ref;
                }}
                data={data}
                modalPlugin={modalPlugin}
              />
            )}

            {modalPlugin.key === 'dependency_analysis' && (
              <DependencyForm
                ref={(ref) => {
                  this.form = ref;
                }}
                data={data}
                modalPlugin={modalPlugin}
              />
            )}

            {modalPlugin.key === 'pinpoint_detection' && (
              <PinpointForm
                ref={(ref) => {
                  this.form = ref;
                }}
                data={data}
                modalPlugin={modalPlugin}
              />
            )}
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, {
            onClick: (e) => {
              this.props.trigger.props.onClick && this.props.trigger.props.onClick(e);
              this.showModal();
            },
          })}

        {isServiceModalOpen && (
          <GuaranteeModal
            isModalOpen={isServiceModalOpen}
            taskName={modalPlugin.name}
            taskKey={modalPlugin.key}
            noFooter
            closeFn={() => {
              this.setState({
                isServiceModalOpen: false,
              });
            }}
          />
        )}
      </React.Fragment>
    );
  }
}
